<?php
namespace Home\Controller;

use Vendor\Page;

class UserController extends ComController
{


    public function _initialize()
    {
        parent::_initialize();
        $this->is_session();
    }
	
	private $_order_body = '书城充值';
	private $_order_goods_tag = '书城充值';
	public function __construct(){

		parent::__construct();
		require_once "./zaomengr_wxPay_api/lib/WxPay.Api.php";
		require_once "./zaomengr_wxPay_api/lib/WxPay.JsApiPay.php";
		//$_SESSION['user'] = null;
	}
	

	
	//用户信息
    public function userinfo(){
	    //dump('111');die;
        $open_id = $_SESSION['user']['open_id'];
        //dump($open_id);die;
        //个人信息
        $user = D('user')->where("open_id='$open_id'")->find();
        //dump($user);die;
        //支付
        $pay_path = D('pay_path')->field('pay_path')->where('status=1')->find();
        //是否已经参加了本次paymoney活动
        $pay_condi['type'] = 4;
        $pay_condi['start_time'] <= date('Y-m-d',time());
        $pay_condi['end_time'] >= date('Y-m-d',time());
        $status = D('activity')->where($pay_condi)->find();
        $is_join = D('payactive_record')->where("open_id='$open_id'")->find();
        if ($status['status']==1 && empty($is_join)){
            $is_show = 1;
        }
        $this->assign('is_show',$is_show);
        $this->assign('open_id',$open_id);
        $this->assign('pay_path',$pay_path['pay_path']);
        $this->assign('user',$user);
        $this->assign('back_domain',$_SERVER['HTTP_HOST']);
        $this->display("index");
    }
	
	public function getsesson(){
		print_r($_SESSION["user"]);
		echo $this->ajaxReturn($_SESSION["user"]);
	}
	
	/**
	 * 充值
	 * */
	public function recharge(){
        //查找支付路径
        $pay_path = D('pay_path')->field('pay_path')->where('status=1')->find();
        //获得用户金额 获取当前章节收费书币
        if($_GET['status'] == 1){
            $pay_book_money = chapter_money();
            $this->assign('pay_book_money',$pay_book_money);
        }
        $map['open_id'] = $_SESSION['user']['open_id'];
        $user = D('user')->where($map)->find();
        //当前用户的书币
        $this->assign('now_money', $user['book_money']);
        //当前用户open_id
		$this->assign('open_id', $_SESSION['user']['open_id']);
		//支付路径
		$this->assign('pay_path', $pay_path['pay_path']);
		//回调回来的域名
		$this->assign('back_domain', $_SERVER['HTTP_HOST']);
 		$this->display();
	}


    /**
     * 冲9元送11元
     */
    public function huikui9(){
        //echo 111;die;
        //查找支付路径
        $pay_path = D('pay_path')->field('pay_path')->where('status=1')->find();
        //获得用户金额 获取当前章节收费书币
        if($_GET['status'] == 1){
            $pay_book_money = chapter_money();
            $this->assign('pay_book_money',$pay_book_money);
        }
        $map['open_id'] = $_SESSION['user']['open_id'];
        $user = D('user')->where($map)->find();
        //当前用户的书币
        $this->assign('now_money', $user['book_money']);
        //当前用户open_id
        $this->assign('open_id', $_SESSION['user']['open_id']);
        //个人信息
        $this->assign('user',$user);
        //支付路径
        $this->assign('pay_path', $pay_path['pay_path']);
        //回调回来的域名
        $this->assign('back_domain', $_SERVER['HTTP_HOST']);
        $this->display('recharge9');
    }

	
	/**
	 * 通过授权支付平台获得平台的OPENID
	 */
	public function getpayopenid(){
		if(empty($_REQUEST["code"]) || empty($_REQUEST["state"])) {
			echo "bad link";
			die;
		}
		//die("111");
		//第二次验证
		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx267a8cb2e31f45f5&secret=82b3733eab959cf442fbd0ca7bbb70fa&code=".$_REQUEST["code"]."&grant_type=authorization_code";
		//echo $url;die;
		$info = weChatCurl($url);		
		//print_r($_GET);
//		echo "<br><br><br><br><br>";
//		print_r($info);
//		die;	
		//更新用户的支付ID
		$rs = D("user")->where(array("open_id"=>$_GET["normal_openid"]))->save(array("pay_open_id"=>$info["openid"]));
		//跳转到用户的充值的页面
		$return_url = "http://".$_GET["return_host"]."/Home/User/recharge";
		header("Location: $return_url");
		
	}	
	
	/**
	 * 小说以外的平台认证
	 */
	public function otherplatformattestation(){
		//print_r($_REQUEST);die;
		if($_GET["open_id"]) {
			//print_r($_GET);die;
			$domain = $_GET["domain"];
			$moudle = $_GET["moudle"];
			$controller = $_GET["controller"];
			$action = $_GET["action"];
			$open_id = $_GET["open_id"];
			$key = $_GET["key"];
			$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx267a8cb2e31f45f5&redirect_uri=http://qikaism.cn/Home/User/setpayopenid/normal_openid/".$open_id."/domain/".$domain."/moudle/".$moudle."/controller/".$controller."/action/".$action."/key/".$key."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";						
			
			//echo $url;die;
			header("Location: $url");
		}		
	}
	
	/**
	 * 小说以外的平台获得支付open_id
	 */
	public function setpayopenid(){
		//print_r($_REQUEST);die;
		if(empty($_REQUEST["code"]) || empty($_REQUEST["state"])) {
			echo "bad link";
			die;
		}
		//die("111");
		//第二次验证
		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx267a8cb2e31f45f5&secret=82b3733eab959cf442fbd0ca7bbb70fa&code=".$_REQUEST["code"]."&grant_type=authorization_code";
		//echo $url;die;
		$info = weChatCurl($url);
		
		//更新用户的支付ID
		//$rs = D("user")->where(array("open_id"=>$_GET["normal_openid"]))->save(array("pay_open_id"=>$info["openid"]));
		//跳转到用户的充值的页面
		$return_url = "http://".$_GET["domain"]."/".$_GET["moudle"]."/".$_GET["controller"]."/".$_GET["action"]."?pay_open_id=".$info["openid"]."&normal_openid=".$_GET["normal_openid"]."&key=".$_GET["key"];
		//echo $return_url;die;
		header("Location: $return_url");		
	}
	
	//原生态微信支付，有时候会临时替代
	public function pay(){
		if($_GET["pay_type"] == "yinping_pay") { //音频平台支付
			$_SESSION["pay_type"] = "yinping_pay";
			if($_GET["pay_money"])
				$_SESSION["money"] = $_GET["pay_money"];
			if($_GET["order_id"])
				$_SESSION["order_id"] = $_GET["order_id"];
			if($_GET["return_url"])
				$_SESSION["return_url"] = $_GET["return_url"];
			if($_GET["target_url"])
				$_SESSION["target_url"] = $_GET["target_url"];
			if($_GET["cancel_url"])
				$_SESSION["cancel_url"] = $_GET["cancel_url"];
			//print_r($_GET);die;
				
			//①、获取用户openid
			$tools = new \JsApiPay();
			$openId = $tools->GetOpenid();
			//die("1111");
			//echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING'];die;
			//②、统一下单		
			$input = new \WxPayUnifiedOrder();
			
			//echo $input->GetResult_code();die;
			//商品描述
			$input->SetBody($this->_order_body);
			//商户订单号
			$out_trade_no = \WxPayConfig::MCHID.date("YmdHis");
			$input->SetOut_trade_no($out_trade_no);
			//总金额,订单总金额，只能为整数,单位为分
			$input->SetTotal_fee($_SESSION["money"]);					
			//交易起始时间
			$input->SetTime_start(date("YmdHis"));
			//交易结束时间
			$input->SetTime_expire(date("YmdHis", time() + 600));
			//商品标记
			$input->SetGoods_tag($this->_order_goods_tag);
			//通知地址,接收微信支付异步通知回调地址 SITE_URL=http://test.paywechat.com/Charge
			$notify_url = $_SESSION["return_url"];
			
			$input->SetNotify_url($notify_url);
			//交易类型
			$input->SetTrade_type("JSAPI");
			$input->SetOpenid($openId);
			
			//附加数据，可以添加自己需要的数据，微信回异步回调时会附加这个数据
			$input->SetAttach($_SESSION["order_id"]);	

	
			//获取订单信息	
			$order = \WxPayApi::unifiedOrder($input);		
			//print_r($order);die;
			//die("111");	
			
			//参数
			$jsApiParameters = $tools->GetJsApiParameters($order);			
			
			//die("222");
			$editAddress = $tools->GetEditAddressParameters();			
			$this->assign('jsApiParameters',$jsApiParameters);
			//print_r($editAddress);die;
			//echo $openId;die;
			
			$this->assign("target_url",$_SESSION["target_url"]);
			$this->assign("cancel_url",$_SESSION["cancel_url"]);
			
			//清除充值选择ID
			$this->display("yinping_pay"); 				
		}
		else{ //小说支付
			if(!empty($_REQUEST["open_id"])){
				$_SESSION["open_id"] = $_REQUEST["open_id"];
			}
			//①、获取用户openid
			$tools = new \JsApiPay();
			$openId = $tools->GetOpenid();
			//echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING'];die;
			//②、统一下单		
			$input = new \WxPayUnifiedOrder();
			//echo $input->GetResult_code();die;
			//商品描述
			$input->SetBody($this->_order_body);
			//商户订单号
			$out_trade_no = \WxPayConfig::MCHID.date("YmdHis");
			$input->SetOut_trade_no($out_trade_no);
			//总金额,订单总金额，只能为整数,单位为分
			if(intval($_SESSION["pay_id"]) == 1)
				$input->SetTotal_fee(20000);
			elseif(intval($_SESSION["pay_id"]) == 2)
				$input->SetTotal_fee(10000);			
			elseif(intval($_SESSION["pay_id"]) == 3)
				$input->SetTotal_fee(5000);						
			elseif(intval($_SESSION["pay_id"]) == 4)
				$input->SetTotal_fee(3000);			
			elseif(intval($_SESSION["pay_id"]) == 6)
				$input->SetTotal_fee(36500);
			elseif(intval($_SESSION["pay_id"]) == 7)
				$input->SetTotal_fee(1000);			
			elseif(intval($_SESSION["pay_id"]) == 8)
				$input->SetTotal_fee(2000);		
			elseif(intval($_SESSION["pay_id"]) == 11)
				$input->SetTotal_fee(1);
			elseif(intval($_SESSION["pay_id"]) == 12)
				$input->SetTotal_fee(9900);				
			//交易起始时间
			$input->SetTime_start(date("YmdHis"));
			//交易结束时间
			$input->SetTime_expire(date("YmdHis", time() + 600));
			//商品标记
			$input->SetGoods_tag($this->_order_goods_tag);
			//通知地址,接收微信支付异步通知回调地址 SITE_URL=http://test.paywechat.com/Charge
			$notify_url = "http://".$_SERVER["HTTP_HOST"]."/Home/User/getback";		
			//echo $_SESSION["user"]["open_id"]."<br>";
			//echo $notify_url;
			$input->SetNotify_url($notify_url);
			//交易类型
			$input->SetTrade_type("JSAPI");
			$input->SetOpenid($openId);		
			//print_r($_SESSION);die;
			//添加订单
			$order_data["open_id"] = $_SESSION["open_id"]; //open_id
			$order_data["addtime"] = date("Y-m-d H:i:s"); //下单时间
			if($_SESSION["pay_id"] == "1") //支付金额
				$order_data["money"] = 20000;
			elseif($_SESSION["pay_id"] == "2")
				$order_data["money"] = 10000;			
			elseif($_SESSION["pay_id"] == "3")
				$order_data["money"] = 5000;					
			elseif($_SESSION["pay_id"] == "4")
				$order_data["money"] = 3000;		
			elseif($_SESSION["pay_id"] == "6")
				$order_data["money"] = 36500;
			elseif($_SESSION["pay_id"] == "7")
				$order_data["money"] = 1000;	
			elseif($_SESSION["pay_id"] == "8")
				$order_data["money"] = 2000;	
			elseif($_SESSION["pay_id"] == "11")
				$order_data["money"] = 1;
			elseif($_SESSION["pay_id"] == "12")
				$order_data["money"] = 9900;
			$order_id = D("order")->add($order_data);
			//附加数据，可以添加自己需要的数据，微信回异步回调时会附加这个数据
			$input->SetAttach($order_id);
	
			//获取订单信息	
			$order = \WxPayApi::unifiedOrder($input);
			if($order['prepay_id'] == ""){ //统一下单失败
				//删除自身订单
				D("order")->where("order_id=".$order_id)->delete();
				//重新跳转请求腾讯下单
				$url = 'http://'.$_SERVER['HTTP_HOST'].'/Home/User/pay?id='.$_SESSION["pay_id"];
				header("Location: ".$url);
				die;
			}
			
			$jsApiParameters = $tools->GetJsApiParameters($order);
			//$testvalue = $order["prepay_id"];
			//print_r($order);
			//D("test")->add(array("test"=>$testvalue));
			//获取共享收货地址js函数参数
			$editAddress = $tools->GetEditAddressParameters();
			
			$this->assign('openId',$openId);
			$this->assign('jsApiParameters',$jsApiParameters);
			//print_r($jsApiParameters);die;
			$this->assign('editAddress',$editAddress);
			//print_r($editAddress);die;
			
			//当前的OPEN_ID获得绑定域名
			$user_rs = D("user")->where("open_id='{$_SESSION["open_id"]}'")->find();
			//echo $_SESSION["open_id"];die;
			//print_r($user_rs);
			//获得落地域名
			$i_map["set_domain"] = $user_rs["domain"];
			$i_map["status"] = 0;
			$d_info = D("domain")->where($i_map)->find();
			//echo D()->getLastSql();die;
			
			//print_r($d_info);die;
			$this->assign("domian", $d_info['show_domain']);
			
			//清除充值选择ID
			//$_SESSION["pay_id"] = null;
			$this->display(); 		
		}
	}
	
	/**
	 * 浦发银行支付
	 * */
	public function pay1(){
		if($_GET["pay_type"] == "yinping_pay") { //音频平台支付
			//var_dump($_GET);
			//die;
			
			//常用参数
			$money = $_GET["pay_money"];
			$pay_open_id = $_GET["pay_open_id"];
			$return_url = $_GET["return_url"];
			$order_id = $_GET["order_id"];
				
			//$order_data["money"] = 100;
			//$order_id = D("order")->add($order_data);
			//获得支付用的openid		
			//$pay_open_id = D("user")->field("pay_open_id")->where(array("open_id"=>$_SESSION["open_id"]))->find();
			
			//公众号支付请求参数
			$arrHashCode = array(
					'requestNo'=>time().srand().srand(), //请求流水号
					'version'=>'V1.1', //版本号
					'productId'=>'0112',
					'transId'=>'16',
					//'agentId'=>'100003',//如果使用代理商，请判断通过代理商的秘钥做交易
					'merNo'=>'310440300024993',
					'subMchId'=>'41828290',
					'subOpenId'=>$pay_open_id,
					'clientIp'=>'120.25.200.227',
					'returnUrl'=>$return_url,
					'notifyUrl'=>$return_url,
					'transAmt'=>$money,
					'orderDate'=>date('Ymd'),
					'orderNo'=>$order_id,
					'commodityName'=>'test'
			);
			
			
			$dateEncrypt = new \Think\encrypt();
			$util = new \Think\Util();
			
			//接口地址区分生产和测试(注:该地址为测试环境地址)
			//$url="http://121.201.32.197:9080/payment-gate-web/gateway/api/backTransReq";
			//$url="http://121.201.111.67:9080/payment-gate-web/gateway/api/backTransReq";
			$url = "http://spdbweb.chinacardpos.com/payment-gate-web/gateway/api/backTransReq";
			//验签处理字段
			$arrHashCode['signature']= urlencode($dateEncrypt->sign($util->SinParamsToString($arrHashCode)));
			//print_r($arrHashCode['signature']);die;
			$post_data=$util->arrayToString($arrHashCode);
			//var_dump($post_data);
			//数据返回
			$rs =  $util->postData($url,$post_data);
			$formfield_start = strpos($rs, "formfield=") + strlen("formfield=");
			$formfield_end = strpos($rs, "}", $formfield_start) + 1;
			$jsApiParameters = substr($rs,$formfield_start, $formfield_end - $formfield_start);
			
			//$this->assign('openId',$_REQUEST["open_id"]);
			
			$this->assign('jsApiParameters',$jsApiParameters);
	//		echo "<meta charset='utf-8'>";
	//		print_r($rs);die;
			
			//当前的OPEN_ID获得绑定域名
			$user_rs = D("user")->where("open_id='{$_SESSION["open_id"]}'")->find();
			//print_r($user_rs);
			//获得落地域名
			$i_map["set_domain"] = $user_rs["domain"];
			$d_info = D("domain")->where($i_map)->find();
			
			//print_r($d_info);die;
			//$this->assign("domian", $d_info['show_domain']);		
			$this->assign("target_url", $_GET["target_url"]);
			$this->assign("cancel_url", $_GET["cancel_url"]);			
			$this->display("yinping_pay");			
		}
		else{ //小说支付
			if(!empty($_REQUEST["open_id"])){
				$_SESSION["open_id"] = $_REQUEST["open_id"];
			}
			
			//添加平台订单
			$order_data["open_id"] = $_SESSION["open_id"]; //open_id
			$order_data["addtime"] = date("Y-m-d H:i:s"); //下单时间
			if($_REQUEST["id"] == "1") //支付金额
				$order_data["money"] = 20000;
			elseif($_REQUEST["id"] == "2")
				$order_data["money"] = 10000;			
			elseif($_REQUEST["id"] == "3")
				$order_data["money"] = 5000;					
			elseif($_REQUEST["id"] == "4")
				$order_data["money"] = 3000;		
			elseif($_REQUEST["id"] == "6")
				$order_data["money"] = 36500;
			elseif($_REQUEST["id"] == "7")
				$order_data["money"] = 1000;	
			elseif($_REQUEST["id"] == "8")
				$order_data["money"] = 2000;
			else {
				$order_data["money"] = 100;
			}
				
			//$order_data["money"] = 100;
			$order_id = D("order")->add($order_data);
			//获得支付用的openid		
			$pay_open_id = D("user")->field("pay_open_id")->where(array("open_id"=>$_SESSION["open_id"]))->find();
			//公众号支付请求参数
			$arrHashCode = array(
					'mch_id'=>'310440300024993', //商户号
					'out_order_no'=>$order_id, //商户订单号
					'pay_platform'=>'WXPAY', //支付平台
					'pay_type'=>'JSAPI', //交易类型
					'payment_fee'=>$order_data["money"], //订单金额
					'cur_type'=>'CNY', //币种
					'body'=>'小说充值', //商品类型
					'notify_url'=>"http://".$_SERVER['HTTP_HOST']."/Home/User/pay_back", //异步通知回调地址
					'bill_create_ip'=>'120.25.200.227', //终端IP
					'remark'=>'小说充值', //订单拓展信息
					'shop_id'=>'1900000109', //门店编号
					'cashier_id'=>'100032434', //收银员ID
					'auth_code'=>'100032434', //支付平台认,支付类型为刷卡时必填
					'openid'=>$pay_open_id["pay_open_id"], //支付平台open_id
					'pay_limit'=>'no_credit', //禁用信用卡					
			);
			//$arrHashCode = json_encode($arrHashCode);
			echo "<meta charset=utf-8>";
			var_dump($arrHashCode);
			ksort($arrHashCode);
			var_dump($arrHashCode);
			
			$sign = strtoupper(md5('biz_content='.json_encode($arrHashCode)."&key=".mch_key));

			
			//公众号支付请求参数
/*			$arrHashCode = array(
					'requestNo'=>time().srand().srand(), //请求流水号
					'version'=>'V1.1', //版本号
					'productId'=>'0112',
					'transId'=>'16',
					//'agentId'=>'100003',//如果使用代理商，请判断通过代理商的秘钥做交易
					'merNo'=>'310440300024993',
					'subMchId'=>'41828290',
					'subOpenId'=>$pay_open_id["pay_open_id"],
					//'subOpenId'=>"o5t0dwWBZt6eW28epeRB8axXk8Sw",
					'clientIp'=>'120.25.200.227',
					'returnUrl'=>"http://".$_SERVER['HTTP_HOST']."/Home/User/pay_back",
					'notifyUrl'=>"http://".$_SERVER['HTTP_HOST']."/Home/User/pay_back",
					'transAmt'=>$order_data["money"],
					'orderDate'=>date('Ymd'),
					'orderNo'=>$order_id,
					'commodityName'=>'test'
			);
			
			
			$dateEncrypt = new \Think\encrypt();
			$util = new \Think\Util();
			
			//接口地址区分生产和测试(注:该地址为测试环境地址)
			//$url="http://121.201.32.197:9080/payment-gate-web/gateway/api/backTransReq";
			//$url="http://121.201.111.67:9080/payment-gate-web/gateway/api/backTransReq";
			$url = "http://spdbweb.chinacardpos.com/payment-gate-web/gateway/api/backTransReq";
			//验签处理字段
			$arrHashCode['signature']= urlencode($dateEncrypt->sign($util->SinParamsToString($arrHashCode)));
			//print_r($arrHashCode['signature']);die;
			$post_data=$util->arrayToString($arrHashCode);
			//var_dump($post_data);
			//数据返回
			$rs =  $util->postData($url,$post_data);
			$formfield_start = strpos($rs, "formfield=") + strlen("formfield=");
			$formfield_end = strpos($rs, "}", $formfield_start) + 1;
			$jsApiParameters = substr($rs,$formfield_start, $formfield_end - $formfield_start);
			
			$this->assign('openId',$_REQUEST["open_id"]);
			$this->assign('jsApiParameters',$jsApiParameters);
	//		echo "<meta charset='utf-8'>";
	//		print_r($rs);die;			
			//当前的OPEN_ID获得绑定域名
			$user_rs = D("user")->where("open_id='{$_SESSION["open_id"]}'")->find();
			//print_r($user_rs);
			//获得落地域名
			$i_map["set_domain"] = $user_rs["domain"];
			$d_info = D("domain")->where($i_map)->find();
			
			//print_r($d_info);die;
			$this->assign("domian", $d_info['show_domain']);		
			$this->display("pay");*/
		}
	}	
	
	/**
	 * 浦发银行支付回调
	 */
	public function pay_back(){
		$bdata = $_REQUEST;
//		foreach($bdata as $key=>$item) {
//			D("test")->add(array("test"=>$key." ".$item));
//		}
//		
//		die;

		if(!empty($bdata["respDesc"]) && $bdata["respDesc"] == "交易成功"){				
			//获得要添加的书币
			//规则暂时如此，不能后台自定义
			if(intval($bdata['transAmt']) == 3000)//30元不加
				$money = $bdata['transAmt'];
			elseif(intval($bdata['transAmt']) == 5000) //50元加3000
				$money = intval($bdata['transAmt']) + 3000;
			elseif(intval($bdata['transAmt']) == 10000) //100元加8000
				$money = intval($bdata['transAmt']) + 8000;
			elseif(intval($bdata['transAmt']) == 20000)
				$money = intval($bdata['transAmt']) + 20000; //200元加20000
			elseif(intval($bdata['transAmt']) == 1000) //10元不加
				$money = intval($bdata['transAmt']);		
			elseif(intval($bdata['transAmt']) == 2000) //20元不加
				$money = intval($bdata['transAmt']);
			elseif(intval($bdata['transAmt']) == 9900) //99元加100
				$money = intval($bdata['transAmt']) + 10000;
			else {										//年会员或者其他充值
				$money = $bdata['transAmt'];
			}
					
			$order = D("order")->where("order_id=".$bdata['orderNo'])->find();//开启事务处理
			if($order["status"] == "0") {
				$model = M();
				$model->startTrans();
				//锁行，订单数据
				$model->table("qw_order")->lock(true)->where("order_id=".$bdata['orderNo']);
				//修改订单状态为支付和支付的时间					
				$order_state = $model->table("qw_order")->where("order_id=".$bdata['orderNo'])->save(array("status"=>1,"paytime"=>date("Y-m-d H:i:s")));	
				
				if($money != 36500) { //普通充值
					//修改用户书币
					$data["book_money"] = array("exp", "book_money+".$money);
					//锁行，用户数据
					$model->table("qw_user")->lock(true)->where("open_id=".$order['open_id']);
					$user_state = $model->table("qw_user")->where("open_id='".$order["open_id"]."'")->save($data);
				}
				else{
					//修改用户书币
					//$data["book_money"] = array("exp", "book_money+".$money);
					//锁行，用户数据
					$model->table("qw_user")->lock(true)->where("open_id=".$order['open_id']);
						
					//修改用户vip状态
					$vip_data["is_vip"] = 1;
					$vip_data["vip_begin_date"] = date("Y-m-d");
					$vip_data["vip_end_date"] = date("Y-m-d", (time() + 24 * 3600 * 365));
					$user_state = $model->table("qw_user")->where("open_id='".$order["open_id"]."'")->save($vip_data);											
				}
	
				//如果其中一条无法执行就回滚
				if($order_state != false) {
					$model->commit();
					//活动反书币
					$this->return_money($order["open_id"]);
				}
				else 
					$model->rollback();
					
				
			}
		}
		else{
			D("test")->add(array("test"=>"支付失败"));
		}
	}
	
	//充值书币活动
	//首充值返书币
	protected function return_money($open_id){
		$row = D('user')->where("open_id = '$open_id'")->find();
		$proxy_open_id = $row['proxy_open_id'];

		//判断是否有上线
		if(!empty($proxy_open_id)){
			//查找订单表首次充值
			$first_count = D('order')->where("open_id = '$open_id' and status = 1")->count();
			$time = date('Y-m-d',time());
			$activity_ratio = D('activity')->field('recharge_money')->where("status = 1 and type = 2 and start_time <= '$time' and end_time >= '$time'")->find();
			if($first_count == 1 and !empty($activity_ratio)){
				$first_charge = D('order')->where("open_id = '$open_id' and status = 1")->order('paytime asc')->find();
				$return_money = intval($first_charge['money'] * $activity_ratio['recharge_money']);
				//查找老用户
				$row_old = D('user')->where("open_id = '$proxy_open_id'")->find();
				$money_data['book_money'] = intval($row_old['book_money']) + $return_money;
				$id = D('user')->where("open_id = '$proxy_open_id'")->save($money_data);
				if($id){
					if($row_old['domain'] == 'www.qichezuoyi.com.cn'){
						$this->sendxintemplateinfo($row_old['domain'],'@'.$row_old['nickname'].'       您推荐的好友'.$row['nickname'].'已首次充值',$row_old['nickname'],$return_money,$proxy_open_id);
					}elseif($row_old['domain'] == 'qikaism.cn'){
						$this->sendzuiquantemplateinfo($row_old['domain'],'@'.$row_old['nickname'].'       您推荐的好友'.$row['nickname'].'已首次充值',$row_old['nickname'],$return_money,$proxy_open_id);
					}				
					
				}
			}		
		}		
	}

	/**
	 * 新生活影音首次充值推送模板信息
	 * */
	protected function sendxintemplateinfo($domain, $title,$old_nickname, $money,$open_id){		
				
		$map["domain"] = $domain;
		$platform = D("platform")->where($map)->find();
		if(intval($platform["out_time"]) > time())	{
			$token = getWeChatToken($platform["appid"],$platform["secret"],$platform["token"]);
		}
		else{
			$token = getWeChatToken($platform["appid"],$platform["secret"]);
		}
		//$token = "uE8o4BowpwHdc732mj869AkKGtrVB0Dumi1Hyu_ifLeSVNILA9Yyt1ZfXKJ8P3FpqPk7zYTEKUwD29O4gTAcoVs_NlY070ytewXeqran8iXXGeMLuzug58Sn3X9H2qVJHWXaACAVKL";
		//$openid = "ols0swsTiYZAdF6cdXxvTJqOWWCk"; 
		
		$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$token";
		$data = '{
		           "touser":"'.$open_id.'",
		           "template_id":"K4BiUn9a3w4bYKHyku2c0lEslYV-KuaazM0ApdXF-4w",
		         
		           "data":{
	                   "first": {
	                       "value":"'.$title.'",
	                       "color":"#173177"
	                   },
	                   "keyword1":{
	                       "value":"推荐首充送书币活动",
	                       "color":"#173177"
	                   },
	                   "keyword2": {
	                       "value":"'.$old_nickname.'",
	                       "color":"#173177"
	                   },
					   "keyword3": {
	                       "value":"'.$money.'书币",
	                       "color":"#173177"
	                   },
	                   "remark":{
	                       "value":"感谢您对本活动的大力支持",
	                       "color":"#173177"
	                   }
		           }
				}';
		$result = weChatCurl($url, 1, $data);
		foreach($result as $k=>$v){
			$test['test'] = $k.'-----'.$v;
					D('test')->add($test);
		}
		//print_r($result);
	}
	
	
	/**
	 * 最全小说首次充值推送模板信息
	 * */
	protected function sendzuiquantemplateinfo($domain, $title,$old_nickname, $money,$open_id){		
				
		$map["domain"] = $domain;
		$platform = D("platform")->where($map)->find();
		if(intval($platform["out_time"]) > time())	{
			$token = getWeChatToken($platform["appid"],$platform["secret"],$platform["token"]);
		}
		else{
			$token = getWeChatToken($platform["appid"],$platform["secret"]);
		}
		//$token = "uE8o4BowpwHdc732mj869AkKGtrVB0Dumi1Hyu_ifLeSVNILA9Yyt1ZfXKJ8P3FpqPk7zYTEKUwD29O4gTAcoVs_NlY070ytewXeqran8iXXGeMLuzug58Sn3X9H2qVJHWXaACAVKL";
		//$openid = "ols0swsTiYZAdF6cdXxvTJqOWWCk"; 
		
		$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$token";
		$data = '{
		           "touser":"'.$open_id.'",
		           "template_id":"7GuUjs3yajSmzNk5b7GssMq7oT7gKeKIOpSoZ73NR8w",
		         
		           "data":{
	                   "first": {
	                       "value":"'.$title.'",
	                       "color":"#173177"
	                   },
	                   "keyword1":{
	                       "value":"推荐首充送书币活动",
	                       "color":"#173177"
	                   },
	                   "keyword2": {
	                       "value":"'.$old_nickname.'",
	                       "color":"#173177"
	                   },
					   "keyword3": {
	                       "value":"'.$money.'书币",
	                       "color":"#173177"
	                   },
	                   "remark":{
	                       "value":"感谢您对本活动的大力支持",
	                       "color":"#173177"
	                   }
		           }
				}';
		$result = weChatCurl($url, 1, $data);
		foreach($result as $k=>$v){
			$test['test'] = $k.'-----'.$v;
					D('test')->add($test);
		}
		//print_r($result);
	}
	 
	
	/**
	 * 原生态微信支付回调
	 */
	public function getback(){		
		require_once "./zaomengr_wxPay_api/example/notify.php";
		$notify = new \PayNotifyCallBack();
		$notify->Handle(false);
		//这里的IsSuccess是我自定义的一个方法，后面我会贴出这个文件的代码，供参考。
		$is_success = $notify->IsSuccess();
		$bdata = $is_success['data'];
		//支付成功
		if($is_success['code'] == 1){
			$news = array(
						'touser' => $bdata['openid'],
						'msgtype' => 'news',
						'news' => array (
							'articles'=> array (
								array('title' => '订单支付成功',
									  'description' => "支付金额：{$bdata['total_fee']}\n"."微信订单号：{$bdata['transaction_id']}\n",
									  'picurl' => '',
									  'url' => '')													
							)
						)
					);
			
			
			//获得要添加的书币
			//规则暂时如此，不能后台自定义
			if(intval($bdata['total_fee']) == 3000)//30元不加
				$money = $bdata['total_fee'];
			elseif(intval($bdata['total_fee']) == 5000) //50元加3000
				$money = intval($bdata['total_fee']) + 3000;
			elseif(intval($bdata['total_fee']) == 10000) //100元加8000
				$money = intval($bdata['total_fee']) + 8000;
			elseif(intval($bdata['total_fee']) == 20000)
				$money = intval($bdata['total_fee']) + 20000; //200元加20000
			elseif(intval($bdata['total_fee']) == 1000) //10元不加
				$money = intval($bdata['total_fee']);		
			elseif(intval($bdata['total_fee']) == 2000) //20元不加
				$money = intval($bdata['total_fee']);
			elseif(intval($bdata['total_fee']) == 9900) //99元加100
				$money = intval($bdata['total_fee']) + 10000;				
			else {										//年会员
				$money = $bdata['total_fee'];
			}
				
			$order = D("order")->where("order_id=".$bdata['attach'])->find();
			if(!empty($order) && intval($order["status"]) == 0) {				
				try{
					//开启事务处理
					$model = M();
					$model->startTrans();
					//锁行，订单数据
					$model->table("qw_order")->lock(true)->where("order_id=".$bdata['attach']);
					//修改订单状态为支付和支付的时间					
					$order_state = $model->table("qw_order")->where("order_id=".$bdata['attach'])->save(array("status"=>1,"paytime"=>date("Y-m-d H:i:s")));
					//$test1 =  $model->getLastSql();
					//D("test")->add(array("test"=>$test1));
	
					
					if($money != 36500) { //普通充值
						//修改用户书币
						$data["book_money"] = array("exp", "book_money+".$money);
						//锁行，用户数据
						$model->table("qw_user")->lock(true)->where("open_id=".$order['open_id']);
						$user_state = $model->table("qw_user")->where("open_id='".$order["open_id"]."'")->save($data);
					}
					else{
						//修改用户书币
						$data["book_money"] = array("exp", "book_money+".$money);
						//锁行，用户数据
						$model->table("qw_user")->lock(true)->where("open_id=".$order['open_id']);
						//修改用户vip状态
						$vip_data["is_vip"] = 1;
						$vip_data["vip_begin_date"] = date("Y-m-d");
						$vip_data["vip_end_date"] = date("Y-m-d", (time() + 24 * 3600 * 365));
						$user_state = $model->table("qw_user")->where("open_id='".$order["open_id"]."'")->save($vip_data);											
					}
					
	//				$test_info = $order_state." ".$user_state;
					
					//添加测试信息
					//$model->table("qw_test")->add(array("test"=>$test_info));
	
					//如果其中一条无法执行就回滚
					if($order_state != false)
						$model->commit();
					else 
						$model->rollback();
				}
				catch(Exception $e){
					D("test")->add(array("test"=>1));
				}
			}
			
			//发送微信支付通知
			$this->sendCustomMessage($news);
		}
		else{//支付失败
			echo '<meta charset="utf-8"/>';
			echo "支付失败";
		}
	}
	
	/**
	 * 支付成功页面
	 * 不可靠的回调
	*/
	public function ajax_PaySuccess(){
		//订单号
		$out_trade_no = I('post.out_trade_no');
		//支付金额
		$total_fee = I('post.total_fee');
		/*相关逻辑处理*/
	}
	
	public function getpayInfo(){
		$pay_info = S("pay_info");
		print_r($page_info);
	}
	
	/**
	 * 送书币显示页面
	 * */
	public function getbookmoney(){
		if(!empty($_SESSION["user"])){
			$this->display();
		}
		else {
			$redirect = $_SERVER['REQUEST_URI'];
			//先判断是否是显示域名
			$map["show_domain"] = $_SERVER['HTTP_HOST'];			
			$domain = D("domain")->where($map)->find();
			if(!empty($domain)) //如果当前域名是显示域名的时候，查询出绑定域名进行跳转
				$url = "http://".$domain['set_domain']."/Home/User/index?redirect=".$redirect;
			else //如果是绑定域名，那么就直接跳转
				$url = "http://".$_SERVER['HTTP_HOST']."/Home/User/index?redirect=".$redirect;
			
			header("Location: ".$url);
			die;
		}
	}
	
	/**
	 * 送书币操作功能
	 * */
	public function ajaxgetmoney(){
		if(!empty($_SESSION["user"])){			
			$qiandao = D("qiandao")->where("open_id='".$_SESSION["user"]["open_id"]."' and qd_date='".date("Y-m-d")."'")->find();
			
			if(empty($qiandao)){				
				//添加书币
				$data["book_money"] = array("exp", "book_money+20");
				$user_state = D("user")->where("open_id='".$_SESSION["user"]["open_id"]."'")->save($data);
				//添加签到信息
				$qiandao_data["open_id"] = $_SESSION["user"]["open_id"];
				$qiandao_data["qd_date"] = date("Y-m-d");
				$qiandao_data["nickname"] = $_SESSION["user"]["nickname"];
				D("qiandao")->add($qiandao_data);
				//$_SESSION["user"]["check_date"] = date("Y-m-d");
				
				$this->ajaxReturn(array("status"=>200));
			}
			else{
				$this->ajaxReturn(array("status"=>300));
// 				$check_start = strtotime($_SESSION["user"]["check_date"]);
// 				$check_end = strtotime(date("Y-m-d"));
// 				if($check_end > $check_start){
// 					//事务处理，锁用户行更新签到书币
// 					M()->startTrans();
// 					$data["book_money"] = array("exp", "book_money+50");
// 					$user_state = D("user")->where("open_id='".$_SESSION["user"]["open_id"]."'")->save($data);
// 					if(!empty($user_state)) {
// 						M()->commit();
// 						$_SESSION["user"]["check_date"] = date("Y-m-d");
// 						$this->ajaxReturn(array("status"=>200));
// 					}
// 					else{
// 						M()->rollback();
// 						$this->ajaxReturn(array("status"=>400));
// 					}
// 				}
// 				else{
// 					$this->ajaxReturn(array("status"=>300));
// 				}
			}
		}
		else {
			$url = "http://".$_SERVER['HTTP_HOST']."/Home/User/index";
			header("Location: $url");
		}		
	}

	public function book_buy(){
	    $open_id = $_SESSION['user']['open_id'];
	    $open_id = 'ojRi10ZWHhU2mN5Yr9ouysc46cD4';
	    $buy = D('')->query("select b.name,b.description from qw_user_buy as a  JOIN qw_novel as b ON a.novel_id = b.id where open_id = '$open_id' group by a.novel_id");
	    //$buy = D('user_buy')->where("open_id = '$open_id'")->join('on ')->group('novel_id desc')->select();
        dump($buy);die;
        $this->display();
    }

    public function help(){
	    $this->display();
    }

    public function paymoney(){
        //查询出用户的消费的金额
        $map['open_id'] = $_SESSION['user']['open_id'];
        $map['status'] = 1;
        $paymoney = D('order')->field('sum(money) as money')->where($map)->fetchSql(false)->find();
        $money = $paymoney['money']/100;
        //dump($money);die;
        $time = date('Y-m-d',time());
        $pids = D('payactive')->alias('a')->field('a.pid,a.pay_id,a.img,a.activity_id,b.id')->join("qw_activity as b on b.id = a.activity_id")->where("a.samount<$money and a.bamount >= $money")->where("b.start_time< '$time' and b.end_time>'$time' and b.status = 1")->fetchSql(false)->find();
        $open_id = $_SESSION[user]['open_id'];
        $record = D('payactive_record')->where("open_id = '$open_id'")->find();
        if (!empty($pids) && empty($record)){
            $user = D('user')->where($map)->find();
            $pay_path = D('pay_path')->field('pay_path')->where('status=1')->find();
            //支付的id
            $this->assign('id',$pids['pay_id']);
            //dump($pids['pay_id']);die;
            //当前用户open_id
            $this->assign('open_id', $_SESSION['user']['open_id']);
            //个人信息
            $this->assign('user',$user);
            //支付路径
            $this->assign('pay_path', $pay_path['pay_path']);
            //回调回来的域名
            $this->assign('back_domain', $_SERVER['HTTP_HOST']);
            //dump($pids['img']);die;
            $this->assign('img',$pids['img']);
            $this->display();
        }else{
            $this->display('paymoney1');
        }

    }
	/**
	 * 推送图文信息
	 * */
	/**
	 * 推送图文信息
	 * */
	public function pushimginfo(){
/*		$domain = $_SERVER['HTTP_HOST'];
		//echo $domain;
		$map["domain"] = $domain;
		$platform = D("platform")->where($map)->find();
		$open_id = $_GET["open_id"] ? $_GET["open_id"] : "ols0swsTiYZAdF6cdXxvTJqOWWCk";
		$title = $_GET["title"] ? $_GET["title"] : "test";
		$description= $_GET["description"] ? $_GET["description"] : "test";
		$picurl= $_GET["picurl"] ? $_GET["picurl"] : "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1495376258189&di=311c70ebe98c4215296f8377b00492a3&imgtype=0&src=http%3A%2F%2Fa4.att.hudong.com%2F38%2F47%2F19300001391844134804474917734_950.png";
		$url = $_GET["url"] ? $_GET["url"] : "https://www.baidu.com/";
		$token = null;
		if(intval($platform["out_time"]) > time())	{
			// 			if($_GET["state"] == "error"){
			// 				$token = S("token");
			// 				if(empty($token)) {
			// 					S("token",null);
			// 					getWeChatToken();
			// 				}
			// 			}
			$token = getWeChatToken($platform["appid"],$platform["secret"],$platform["token"]);
		}
		else{
			$token = getWeChatToken($platform["appid"],$platform["secret"]);
		}
		
		$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$token";
// 		$data["touser"] = "oaKAexCl9aOYqJma9gXJ40FfdJjE";
// 		$data["msgtype"] = "news";
// 		$data["news"]["articles"][] = array("title"=>"test","description"=>"test","url"=>"https://www.baidu.com","picurl"=>"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1495376258189&di=311c70ebe98c4215296f8377b00492a3&imgtype=0&src=http%3A%2F%2Fa4.att.hudong.com%2F38%2F47%2F19300001391844134804474917734_950.png");
		$data = '{
				    "touser":"'.$open_id.'",
				    "msgtype":"news",
				    "news":{
				        "articles": [
					         {
					             "title":"'.$title.'",
					             "description":"'.$description.'",
					             "url":"'.$url.'",
					             "picurl":"'.$picurl.'"
					         }
				         ]
				    }
				}
		';
		$result = weChatCurl($url, 1, $data);
		print_r($result);*/
		
	}

    public function phoneAuth(){
        header("Content-Type: text/html; charset=UTF-8");
        $user = $_SESSION['user'];
        if( empty( $user['phone'] ) ){
            $this->assign("havephone", "0");
        }else{
            $this->assign("havephone", "1");
            $da = D("user")->where(['open_id'=>$user['open_id']])->find();
            $this->assign("phone", $da['phone'] );
//            $this->assign("phone", "fdspfkpoasdijfpoiasdhp");
        }

        if( IS_POST ){
            $phone = $_POST['phone'];
            $vericode = $_POST['vericode'];
            if( $phone == ""  ){
                echo "电话号码不能为空<a href='".U('User/phoneAuth')."'>返回上一页</a>";
                die();
            }
            if( $vericode == ""  ){

                echo "验证码不能为空<a href='".U('User/phoneAuth')."'>返回上一页</a>";
                die();
            }

            if( $_SESSION['ms_code'] !=  $vericode ){
                echo "验证码不正确<a href='".U('User/phoneAuth')."'>返回上一页</a>";
                die();
            }

            $map['open_id'] = $_SESSION['user']['open_id'];
            $map['status'] = 1;
            $user = D('user')->where($map)->find();
            $user['phone'] = $phone;
            D('user')->save( $user );

            $_SESSION['user'] = $user;
            $this->assign("phone",$phone );
//            echo D('user')->getLastSql();

        }

        $this->display();

    }

    public function veriphonesendms(){
        $phone = $_GET['phone'];
        $paycode = rand(1000,9999);
        file_put_contents("testtest.txt", $paycode, FILE_APPEND);
        file_put_contents("testtest.txt", "\r\n", FILE_APPEND);
        $content='短信验证码为:'.$paycode.',请勿将验证码提供给他人.';
        $ret = $this->send_newsms($phone,$content);
        if($ret){
            $_SESSION['ms_code']=$paycode;
            $this->ajaxReturn(['status'=>1,'message'=>'验证码发送成功！']);
        }else{
            $this->ajaxReturn(['status'=>0,'Code'=>'','message'=>'短信发送失败！']);
        }
    }


    public function send_newsms($mobile,$content){
    		header("Content-Type: text/html; charset=UTF-8");
    		$flag = 0;
    		$params='';//要post的数据
    		//以下信息自己填以下
    		$argv = array(
    				'un'=>'N3176154',     //必填参数。用户账号
    				'pw'=>'yUqjeDJgYC482a',     //必填参数。（web平台：基本资料中的接口密码）
    				'msg'=>"【萌鲨互娱】".$content,   //必填参数。发送内容（1-500 个汉字）UTF-8编码
    				'phone'=>$mobile,   //必填参数。手机号码。多个以英文逗号隔开
    				'ex'=>'',    //可选参数，扩展码，用户定义扩展码，只能为数字
    				'rd'=>'1' //是否需要状态报告，0表示不需要，1表示需要
    		);

    		foreach ($argv as $key=>$value) {
    			if ($flag!=0) {
    				$params .= "&";
    				$flag = 1;
    			}
    			$params.= $key."="; $params.= urlencode($value);// urlencode($value);
    			$flag = 1;
    		}
    		$url = "http://smssh1.253.com/msg/send?".$params; //提交的url地址

    		$con= file_get_contents($url);  //获取信息发送后的状态
            $p1 = strpos( $con, "," );
            $p2 = substr( $con, $p1+1, 1 );
    		if($p2 == '0'){
    			return true;
    		}else{
    			return false;
    		}
    	}


}